package com.wangijun.yuan.admin.system.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangijun.yuan.admin.base.YuanAdminConst;
import com.wangijun.yuan.admin.system.domain.SysSerial;
import com.wangijun.yuan.admin.system.mapper.SysSerialMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class SysSerialService extends ServiceImpl<SysSerialMapper, SysSerial> {

    // 序列长度不够时填充字段
    final String padStr = "0";

    /**
     * 获取序列
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String getSerial(YuanAdminConst.SerialType type) {
        SysSerial serial = this.getById(type.name());
        if (serial == null) { // 不存在序列的情况
            SysSerial saveTemp = new SysSerial();
            saveTemp.setSerialType(type.name());
            saveTemp.setSerialNo(1);
            saveTemp.setGenerateDate(DateUtil.date().toString(type.getType().getFormat()));
            this.save(saveTemp);
            return StrUtil.padPre(String.valueOf(saveTemp.getSerialNo()), type.getLength(), padStr);
        } else {
            if (Objects.requireNonNull(type.getType()) == YuanAdminConst.SerialType.RestType.NONE) {
                SysSerial updateTemp = new SysSerial();
                updateTemp.setSerialType(serial.getSerialType());
                updateTemp.setSerialNo(serial.getSerialNo() + 1);
                this.updateById(updateTemp);
                return StrUtil.padPre(String.valueOf(updateTemp.getSerialNo()), type.getLength(), padStr);
            }
            String formatDate = DateUtil.date().toString(type.getType().getFormat());
            SysSerial saveTemp = new SysSerial();
            saveTemp.setSerialType(type.name());
            if (formatDate.equals(serial.getGenerateDate())) {
                saveTemp.setSerialNo(serial.getSerialNo() + 1);
                this.updateById(saveTemp);
            } else {
                saveTemp.setGenerateDate(DateUtil.date().toString(type.getType().getFormat()));
                saveTemp.setSerialNo(1);
                this.save(saveTemp);
            }
            return StrUtil.padPre(String.valueOf(saveTemp.getSerialNo()), type.getLength(), padStr);
        }
    }
}
